package com.tanhua.dubbo.api;

import cn.itcast.eunms.CommentType;
import cn.itcast.mongo.Comment;
import cn.itcast.mongo.Video;
import cn.itcast.tanhua.api.VideoApi;
import cn.itcast.vo.PageResult;
import com.tanhua.dubbo.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String save(Video video) {
        //1、设置属性
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(video);
        //3、返回对象id
        return video.getId().toHexString();
    }

    /**
     * 根据vid查询小视频列表
     */
    @Override
    public List<Video> findMovementsByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public Boolean hasComment(ObjectId id, Long userId, CommentType like) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(String.valueOf(id)))
                .and("commentType").is(like.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query,Comment.class);
    }

    /**
     * 分页查询小视频数据
     */
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").in(userId));
        long count = mongoTemplate.count(query, Video.class);
        query.limit(pagesize).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }

    @Override
    public Integer likeTest(Comment comment) {
        //1、查询动态
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        //2、向comment对象设置被评论人属性
        if(video != null) {
            comment.setPublishUserId(video.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comment);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video videos = mongoTemplate.findAndModify(query, update, options, Video.class);
        //5、获取最新的评论数量，并返回
        return videos.statisCount(comment.getCommentType() );
    }

    @Override
    public Integer delete(Comment comment) {
        //1、删除Comment表数据
        Criteria criteria = Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query,Comment.class);
        //2、修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",-1);
        }else if (comment.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video video = mongoTemplate.findAndModify(movementQuery, update, options, Video.class);
        //5、获取最新的评论数量，并返回
        return video.statisCount(comment.getCommentType() );

    }

    @Override
    public Boolean hasCommentTest(String id, Long userId, CommentType like) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(id))
                .and("commentType").is(like.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query,Comment.class);

    }

    @Override
    public Integer saveTest(Comment comments) {
        //1、查询动态
        Video video = mongoTemplate.findById(comments.getPublishId(), Video.class);
        //2、向comment对象设置被评论人属性
        if(video != null) {
            comments.setPublishUserId(video.getUserId());
        }
        //3、保存到数据库
        mongoTemplate.save(comments);
        //4、更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comments.getPublishId()));
        Update update = new Update();
        if(comments.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount",1);
        }else if (comments.getCommentType() == CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Video video1 = mongoTemplate.findAndModify(query, update, options, Video.class);
        //5、获取最新的评论数量，并返回
        return video1.statisCount(comments.getCommentType() );
    }

    @Override
    public List<Comment> findComments(ObjectId id, CommentType comment, Integer page, Integer pagesize) {
        //1、构造查询条件
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(String.valueOf(id))).and("commentType")
                .is(comment.getType()))
                .skip((page -1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //2、查询并返回
        return mongoTemplate.find(query,Comment.class);
    }

    @Override
    public Boolean CommentTest(String id, Long userId, CommentType focus) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(String.valueOf(id)))
                .and("commentType").is(focus.getType());
        Query query = Query.query(criteria);
        return mongoTemplate.exists(query,Comment.class); //判断数据是否存在

    }
}